"""命名实体识别服务"""
import logging
from typing import Optional, Dict

from app.models.legalbert import extract_entities
from app.schemas.requests import NERResponse, Entity

logger = logging.getLogger(__name__)


async def extract_entities_service(
    text: str, 
    label_map: Optional[Dict[int, str]] = None
) -> NERResponse:
    """
    命名实体识别服务
    
    Args:
        text: 输入文本
        label_map: 标签映射字典
        
    Returns:
        NER 结果
    """
    try:
        # 提取实体
        entities_data = extract_entities(text, label_map=label_map)
        
        # 转换为 Entity 模型列表
        entities = [
            Entity(
                text=entity["text"],
                label=entity["label"],
                start=entity["start"],
                end=entity["end"]
            )
            for entity in entities_data
        ]
        
        return NERResponse(
            text=text,
            entities=entities,
            entity_count=len(entities)
        )
    except Exception as e:
        logger.error(f"命名实体识别失败: {str(e)}", exc_info=True)
        raise ValueError(f"命名实体识别失败: {str(e)}")

